define(function (require) {

    require('./repreorder-detail-tpl');
    require('./resend-form-tpl');

    var Tpl = juicer.templates['repreorder-detail.juicer.html'];
    var resendFormTpl = juicer.templates['resend-form.juicer.html'];

    var rePreOrder = {

        detailEntry: {},

        load: false,

        init: function (data) {
            var self = this;
            CRM.request({
                "type": 'POST',
                "url": CRM.getOuterUrl("/logisticscentral/crm/stockout/queryByBizOrderIdForResend"),
                "dataType": "json",
                "async": false,
                contentType: "application/json",
                "data": JSON.stringify({
                    "bizOrderId": data.orderId
                }),
                "success": function (req) {
                    if (req.status) {
                        if (req.entry && req.entry.length > 0) {
                            CRM.request({
                                "type": 'POST',
                                "url": CRM.API.queryOrder,
                                "dataType": "json",
                                "data": JSON.stringify({
                                    "bizOrderId": req.entry[0].bizOrderId
                                }),
                                "success": function (orderReq) {
                                    var entry = orderReq.entry[0];
                                    if (orderReq.status) {
                                        resendForm.detailEntry = {
                                            bizOrderId:req.entry[0].bizOrderId,
                                            buyerMobile:req.entry[0].buyerMobile,
                                            districtName:req.entry[0].districtName,
                                            buyerAddress:req.entry[0].buyerAddress,
                                            buyerNick:req.entry[0].buyerNick,
                                            buyerCityCode:req.entry[0].buyerCityCode,
                                            items:entry.subOrders
                                        };
                                        resendForm.build();
                                        resendForm.initDivision(req.entry[0].buyerCityCode,req.entry[0].districtName);
                                        resendForm.initValidator();
                                        resendForm.bindEvent();
                                    } else {
                                        CRM.showDialog(req.message)
                                    }
                                }
                            });
                        } else {
                            self.detailEntry = data;
                            self.build();
                            self.initBuyAmount();
                            self.initDivision();
                            self.bindEvent();
                            self.initValidator();
                        }
                    } else {
                        CRM.showDialog(req.message);
                    }
                }
            });
        },
        bindEvent: function () {
            var self = this;
            $("#sendRepreorder_btn").on('click', function () {
                self.doSendrepreorder();
            });
        },
        /**
         * 界面渲染
         */
        build: function () {
            CRM.showModal(Tpl({
                "data": this.detailEntry
            }), $('body'));
        },
        /**
         * 初始化重发数量
         */
        initBuyAmount: function () {
            var self = this;
            $("#resendAmount").html("");
            for (var _i = 1; _i <= self.detailEntry.buyAmount; _i++) {
                $("#resendAmount").append("<option value='" + _i + "'>" + _i + "</option>");
            }
            $("#resendAmount").val(self.detailEntry.buyAmount);
        },
        /**
         * 获取区域信息
         */
        initDivision: function () {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/api/rest/division.do"),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                "data": {
                    "code": self.detailEntry.cityCode
                },
                "success": function (req) {
                    if (req.code && req.code == 10000) {
                        $("#district").html("");
                        $.each(req.data.division.subDivisions, function (index, item) {
                            $("#district").append("<option value='" + item.name + "'>" + item.name + "</option>");
                        });
                        if (self.detailEntry.district < 0) {
                            $("#district").val(self.detailEntry.community);
                        } else {
                            CRM.request({
                                "type": 'GET',
                                "url": CRM.API.landmarkInfo + "landmarkid=" + self.detailEntry.district,
                                "dataType": "json",
                                xhrFields: {
                                    withCredentials: false
                                },
                                "success": function (req) {
                                    if (req.doc) {
                                        if (req.doc.address) {
                                            $("#district").val(req.doc.district);
                                            $("#address").val(req.doc.address + req.doc.name + $("#address").val());
                                        }
                                    } else {
                                        if (req.address) {
                                            $("#district").val(req.district);
                                            $("#address").val(req.address + req.name + $("#address").val());
                                        }
                                    }
                                }
                            });
                        }
                    } else {
                        CRM.showDialog(req.msg);
                    }
                }
            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#repreorder_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    mobile: {
                        message: '手机号码输入错误',
                        validators: {
                            notEmpty: {
                                message: '手机号码不能为空'
                            },
                            phone: {
                                country: 'CN',
                                message: '请输入正确的电话格式'
                            }
                        }
                    },
                    reason: {
                        message: '发起原因输入错误',
                        validators: {
                            notEmpty: {
                                message: '发起原因不能为空'
                            }

                        }
                    }
                }
            });
        },
        /**
         * 重发
         */
        doSendrepreorder: function () {
            $("#repreorder_form").data('bootstrapValidator').resetForm();
            $("#repreorder_form").data('bootstrapValidator').validate();
            var dataString, _data = {};
            $($("#repreorder_form").serializeArray()).each(function () {
                _data[this.name] = this.value;
            });
            if ($("#repreorder_form").data('bootstrapValidator').isValid()) {
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl("/trade/order/resendOrder"),
                    "dataType": "json",
                    contentType: "application/x-www-form-urlencoded",
                    "data": _data,
                    "success": function (req) {
                        if (req.status) {
                            $('#refund-detail-modal').modal('hide');
                            window.doSearch();
                            CRM.showDialog("重发成功！");
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }
        }
    };

    /**
     * 新版重发
     * @type {{}}
     */
    resendForm = {
        detailEntry: {},

        load: false,
        init: function (data) {
            var self = this;

        },
        bindEvent: function () {
            var self = this;
            $("#resend_btn").on('click', function () {
                self.doResend();
            });
        },
        /**
         * 界面渲染
         */
        build: function () {
            CRM.showModal(resendFormTpl({
                "data": this.detailEntry
            }), $('body'));
        },
        /**
         * 获取区域信息
         */
        initDivision: function (_buyerCityCode,_districtName) {
            var self = this;
            CRM.request({
                "type": 'GET',
                "url": CRM.getOuterUrl("/api/rest/division.do"),
                "dataType": "json",
                contentType: "application/x-www-form-urlencoded",
                "data": {
                    "code": _buyerCityCode
                },
                "success": function (req) {
                    if (req.code && req.code == 10000) {
                        $("#districtName").html("");
                        $.each(req.data.division.subDivisions, function (index, item) {
                            $("#districtName").append("<option value='" + item.name + "'>" + item.name + "</option>");
                        });
                        if (_districtName) {
                            $("#districtName").val(_districtName);
                        }
                    } else {
                        CRM.showDialog(req.msg);
                    }
                }
            });
        },
        /**
         * 表单验证初始化
         */
        initValidator: function () {
            $('#resend_form').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    mobile: {
                        message: '手机号码输入错误',
                        validators: {
                            notEmpty: {
                                message: '手机号码不能为空'
                            },
                            phone: {
                                country: 'CN',
                                message: '请输入正确的电话格式'
                            }
                        }
                    },
                    reason: {
                        message: '发起原因输入错误',
                        validators: {
                            notEmpty: {
                                message: '发起原因不能为空'
                            }
                        }
                    }
                }
            });
        },
        /**
         * 重发
         */
        doResend: function () {
            $("#resend_form").data('bootstrapValidator').resetForm();
            $("#resend_form").data('bootstrapValidator').validate();
            var dataString, _data = {};
            $($("#resend_form").serializeArray()).each(function () {
                _data[this.name] = this.value;
            });
            _data.items = {};
            $("select[id^='items_']").each(function(_index,_obj){
                _data.items[$(_obj).attr("data-temId")] = $(_obj).val();
            })
            if ($("#resend_form").data('bootstrapValidator').isValid()) {
                CRM.request({
                    "type": 'POST',
                    "url": CRM.getOuterUrl("/logisticscentral/crm/order/resend"),
                    "dataType": "json",
                    "data": JSON.stringify(_data),
                    "success": function (req) {
                        if (req.status) {
                            $('#resend-detail-modal').modal('hide');
                            window.doSearch();
                            CRM.showDialog("重发成功！");
                        } else {
                            CRM.showDialog(req.message);
                        }
                    }
                });
            }
        }
    }


    return rePreOrder;

});